<!-- 通报modal -->
<template>
  <a-modal :bodyStyle="{ padding: '0', 'max-height': '80vh', 'overflow-y': 'auto' }" :title="title" :width="1000" :maskClosable="false" :visible="visible" @cancel="visible = false" :button_loading="button_loading">
    <a slot="footer">
      <a-button @click="visible = false">{{ cancelText }}</a-button>
      <a-button v-if="okText == '保存' && actionType != 'view' " type="primary" @click="handleSubmit">{{
        okText
    }}</a-button>
    </a>
    <a-spin :indicator="indicator" :spinning="spinning" :tip="tip">
      <div class="spin-content">
        <a-form :form="form" :class="{ disable: actionType == 'view' ? true : false }">
          <a-row :gutter="16">
            <a-col class="gutter-row" :span="24">
              <a-form-item v-bind="formItemLayout1" label="关联人员">
                <span v-for="(item, idx) in SupervisionObjectNames" :key="idx" class="tabs_span">{{ item }} <a-icon type="close" style="margin-left: 10px;" @click="handleDelUser(idx)" /></span>

                <a-button type="link" @click="handleSelectUser">
                  选择人员
                </a-button>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="24">
              <a-form-item v-bind="formItemLayout1" label="活动标题">
                <a-input placeholder="填写活动标题" v-decorator="[
        'title',
        { rules: [{ required: true, message: '请填写活动标题!' }] },
    ]" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="24">
              <a-form-item v-bind="formItemLayout1" label="活动时间">
                <a-date-picker :show-time="{ format: 'HH:mm' }" format="YYYY-MM-DD HH:mm" v-decorator="[
        'activityTime',
        {
            rules: [
                { required: true, message: '请选择活动时间!' },
            ],
        },
    ]" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="24">
              <a-form-item v-bind="formItemLayout1" label="活动人数">
                <a-input-number placeholder="填写活动人数" :min="1" :max="9999999" v-decorator="[
        'persons',
        { rules: [{ required: true, message: '请填写活动人数!' }] },
    ]" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="24">
              <a-form-item v-bind="formItemLayout1" label="活动时长">
                <a-input-number placeholder="填写活动时长" :min="1" :max="9999999" v-decorator="[
        'duration',
        { rules: [{ required: true, message: '请填写活动时长!' }] },
    ]" /> 小时
              </a-form-item>
            </a-col>

            <a-col class="gutter-row" :span="24">
              <a-form-item v-bind="formItemLayout1" label="活动内容">
                <a-textarea placeholder="活动内容" :rows="4" v-decorator="['context']" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="24">
              <a-form-item v-bind="formItemLayout1" label="活动照片">

                <a-upload :action="a" list-type="picture-card" :headers="headers" :file-list="fileList" @preview="handlePreview" @change="handleChange" :beforeUpload="beforePhotoUpload">
                  <div v-if="fileList.length < 8">
                    <a-icon type="plus" />
                    <div class="ant-upload-text">
                      上传
                    </div>
                  </div>
                </a-upload>

              </a-form-item>
            </a-col>
          </a-row>
        </a-form>

      </div>
    </a-spin>
    <photo-modal ref="photomodal"></photo-modal>
    <user-modal ref="userModal" @getList="handelGetUser" :list="userSelect"></user-modal>

  </a-modal>

</template>

<script>
import PhotoModal from '@/views/photoModal'
import userModal from './userComponent'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getImg } from '@/api/students'
import { mergeArraysIntoObjects } from '@/utils/util'
export default {
  //import引入的组件需要注入到对象中才能使用
  components: { PhotoModal, userModal },
  props: {
    actionType: {
      type: String,
      required: false,
      default: "add",
    },

  },
  data () {
    //这里存放数据
    return {
      a: null,
      headers: {
        authorization: 'authorization-text',
      },
      action: "add",
      currentId: null,
      CodeDisabled: false,
      required: false,
      indicator: <a-icon type="loading" style="font-size: 24px" spin />,
      form: this.$form.createForm(this),
      button_loading: false,
      spinning: false,
      tip: null,
      title: "查看",
      visible: false,
      okText: "保存",
      cancelText: "取消",
      notificationTypeList: [],
      supervisionList: [],
      Photoloading: false,
      fileList: [],
      PhotoUrlDb: {},
      PhotoUrl: '',
      PhotoUrlDbString: '',
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
      },
      formItemLayout1: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
      },
      SupervisionObjectIDs: [],
      SupervisionObjectNames: [],
      userSelect: []
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //生命周期 - 创建完成（可以访问当前this实例）
  created () {

  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {

  },
  //方法集合
  methods: {
    view (data) {
      if (data) {
        Object.assign(this, {
          spinning: true,
          visible: true,
          CodeDisabled: false,
          currentId: data.id,
        });
        this.initData(data);
      } else {
        this.visible = true;
        this.form.resetFields()
        this.currentId = null;
        this.fileList = []
      }
      switch (this.actionType) {
        case "add":
          this.okText = '保存'
          this.title = "添加活动";
          break;
        case "edit":
          this.okText = '保存'
          this.title = "编辑活动";
          break;
        case "view":
          this.title = "查看活动";
          this.okText = "取消";
          break;
      }
    },
    handlePreview (file) {

      this.$refs.photomodal.view(file)
    },

    handleSelectUser () {
      this.$refs.userModal.view()
    },

    closeModal () {
      this.form.resetFields()
      this.visible = false
    },

    handleDelUser (idx) {
      this.SupervisionObjectIDs.splice(idx, 1);
      this.SupervisionObjectNames.splice(idx, 1);
    },

    handelGetUser (params) {
      console.log(params)
      this.SupervisionObjectIDs = params.map(el => { return el.value })
      this.SupervisionObjectNames = params.map(el => { return el.label })

    },

    handleChange ({ file, fileList }) {
      this.fileList = fileList;
      if (file.status === 'error') {
        this.$message.error(`认证过期:${file.response}`)
      }
      if (file.status === 'uploading') {
        this.Photoloading = true
        return
      }
      if (file.status === 'done') {
        this.PhotoUrlDb = file.response
        this.PhotoUrl = getImg(`${this.PhotoUrlDb.Path}/${this.PhotoUrlDb.NewFileName}`)
        this.PhotoUrlDbString = `${this.PhotoUrlDb.Path}/${this.PhotoUrlDb.NewFileName}`
        this.Photoloading = false
      }

      // console.log(11122222,fileList)
    },


    initData (data) {
      setTimeout(() => {
        this.spinning = false;
        this.form.setFieldsValue({
          ...data,
          activityTime: this.$moment(data.activityTime),
        });
        this.fileList = []
        this.userSelect = mergeArraysIntoObjects(data.SupervisionObjectIDs, data.SupervisionObjectNames),
          this.PhotoUrlDb = data.ActivityImages
        this.SupervisionObjectIDs = data.SupervisionObjectIDs
        this.SupervisionObjectNames = data.SupervisionObjectNames
        if (data.ActivityImages && data.ActivityImages.length > 0) {
          data.ActivityImages.forEach(item => {
            const a = {
              uid: String(item.ID),
              name: String(item.ID),
              status: 'done',
              url: getImg(`${item.Path}/${item.NewFileName}`)
            }
            this.fileList.push(a)
          })
        } else {
          this.fileList = []
        }

      }, 500);
    },

    handleSubmit () {
      let _this = this
      _this.form.validateFields((err, values) => {
        if (!(this.SupervisionObjectIDs && this.SupervisionObjectIDs.length > 0)) {
          this.$message.error('请先选择人员')
          return
        }
        console.log('555555', _this.PhotoUrlDb)
        if (!err) {
          let Uploads = []
          this.fileList.map(aa => {
            if (aa.scan) {
              aa.response && Uploads.push(aa.response)
            }
            if (!aa.url && !aa.scan) {
              aa.response && Uploads.push(aa.response)
            }
            if (aa.url && !aa.scan) {
              Uploads.push(_this.PhotoUrlDb.find(a => a.ID == aa.uid))
            }

          })
          let params = {
            ...values,
            id: _this.currentId,
            ActivityImages: Uploads,
            SupervisionObjectIDs: _this.SupervisionObjectIDs,
            SupervisionObjectNames: _this.SupervisionObjectNames,
            activityTime: _this.$moment(values.activityTime).format('YYYY-MM-DD')
          }
          console.log('Received values of form: ', params);
          _this.$emit("save", { ...params });
        }
      });
    },
    beforePhotoUpload (file) {


      const token = Vue.ls.get(ACCESS_TOKEN) && Vue.ls.get(ACCESS_TOKEN).token
      this.headers = {
        authorization: 'Bearer ' + token,
      }
      this.a = process.env.VUE_APP_API_BASE_URL + `/api/Upload/uploadImg?tablename=Activity&signname=ActivityImages`
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('您只能上传JPG或PNG!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('必须小于2MB!')
      }
      return isJpgOrPng && isLt2M
    },
  },
}
</script>
<style lang='less' scoped>
//@import url(); 引入公共css类
.spin-content {
  padding: 20px;
}
.tabs_span {
  display: inline-block;
  padding: 0 5px;
  margin-right: 10px;
  border-radius: 5px;
  border: 1px solid #dddddd;
}

.disable {
  pointer-events: none;
}
</style>